import webpack from "webpack";
const merge = require('webpack-merge');
import WebpackDevServer from 'webpack-dev-server';
const portfinder = require('portfinder') //监测端口占用的工具
const config = require('./webpack.dev.js');
const tool = require('./tool.js');
const util = require('./util.js');

let dev = async (port) => {
    const siteName = await util.getRunPath();

    const baseConfig = merge(config(siteName), tool.getUserConfig());
    let devPort = 8083;
    await portfinder
        .getPortPromise({
            port: baseConfig.devServer.port || port || devPort
        })
        .then(port => {
            devPort = port;
            //
            // `port` is guaranteed to be a free port
            // in this scope.
            //
        })
        .catch(err => {
            console.log(err)
            //
            // Could not get a free port, `err` contains the reason.
            //
        });

    new WebpackDevServer(webpack(baseConfig), baseConfig.devServer)
        .listen(devPort, 'localhost', function (err, result) {
            if (err) {
                console.log(err);
            }
    });
}

module.exports = dev;
